#include "cell_main.h"
#include "ui_cell_main.h"
#include "dlg_createfile.h"

#include <QFile>
#include <QDebug>
#include <QFileDialog>
#include <QMessageBox>

QString cell_main::_curFileName;

cell_main::cell_main(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::cell_main)
{
    ui->setupUi(this);
    this->setWindowTitle("记事本");
}

cell_main::~cell_main()
{
    delete ui;
}

void cell_main::setcurFileName(QString filename)
{
    cell_main::_curFileName = filename;
}

void cell_main::askIfSaveCurFile()
{
    QMessageBox msgBox;
    msgBox.setText("是否保存当前文件? ");
    msgBox.setStandardButtons(QMessageBox::SaveAll | QMessageBox::No);
    msgBox.setDefaultButton(QMessageBox::Save);
    int retmsg = msgBox.exec();
    if(retmsg == QMessageBox::SaveAll) {
        on_actionSave_triggered(); //保存当前文件
    }
    else if(retmsg == QMessageBox::No) {
        this->_curFileName.clear(); //清除当前文件
    } else {}
}

//新建文件
void cell_main::on_actionNew_triggered()
{
    //询问用户是否保存当前文件
    if(!this->_curFileName.isEmpty()) {
        askIfSaveCurFile();
    }
    //新建文件
    dlg_createFile dlg_cf;
    int retexe = dlg_cf.exec();
    if(retexe == 1) {
        QMessageBox::information(nullptr, "信息", "新建成功!   ");
        openCurFile(); //打开新建的文件
    }
}

//打开当前文件
void cell_main::openCurFile()
{
    QFile file(this->_curFileName);
    bool ret = file.open(QIODevice::ReadOnly);
    if(!ret) {
        qDebug() << "open file err>";
        QString err = file.errorString();
        QMessageBox::information(nullptr, "提示", "打开失败!   ");
    }
    qDebug() << "open file done";
    QByteArray array = file.readAll();
    ui->textEdit->setText(static_cast<QString>(array));
    file.close();
}

//打开文件
void cell_main::on_actionOpen_triggered()
{
    if(!this->_curFileName.isEmpty()) {
        askIfSaveCurFile();
    }

    //用户选择文件
    QString filename = QFileDialog::getOpenFileName(this, tr("选择文件"), "D:\\", tr("Text files (*.txt)"));
    if(!filename.isEmpty()) {
        this->_curFileName = filename; //记录当前文件
        openCurFile();
    }
}

//保存文件
void cell_main::on_actionSave_triggered()
{
    QFile file(this->_curFileName);
    bool retopen = file.open(QIODevice::WriteOnly);
    if(!retopen) {
        qDebug() << "open file err";
    }
    QString strTextEditCont = ui->textEdit->toPlainText();
    qint64 retwr = file.write(strTextEditCont.toUtf8());
    if(retwr == -1) { qDebug() << "write file err"; }
    else { QMessageBox::information(nullptr, "提示", "保存成功!   "); }
    file.close();
}

